using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;

namespace TheLogWatcher
{
    class AccessDataHandler
    {
        public AccessDataHandler(DataAccess dataAccess)
        {
            dataAccess.FnProvider.ResetFileIterator();
            this.dataAccess = dataAccess;
        }

        private DataAccess dataAccess;
        private Dictionary<MessageTypes, long[]> lineIndexes;

        public Dictionary<MessageTypes, long[]> LineIndexes
        {
            get { return lineIndexes; }
            //set { lineIndexes = value; }
        }

        public void prepareDataBuffering()
        {
            // The only thing we have to do here is counting available
            // data rows (needed for ReadActiveRows method).
            this.dataAccess.FnProvider.ResetFileIterator();
            LogFile logfile = this.dataAccess.FnProvider.GetNextFile();
            while (logfile != null)
            {
                FileStream fileStream = File.OpenRead(logfile.Filename);
                LogfileIndexer indexer = new LogfileIndexer(fileStream);
                indexer.countLinesOnly(this.dataAccess);
                logfile = this.dataAccess.FnProvider.GetNextFile();
            }
        }

        /// <summary>
        ///     Reads the line indexes.
        ///     <b>NOTE:</b>
        ///     Currently this method only support single file handling.
        ///     Need to implement a merging Hashtable algorithm.
        /// </summary>
        public void prepareLineIndexing()
        {
            this.dataAccess.FnProvider.ResetFileIterator();
            LogFile logfile = this.dataAccess.FnProvider.GetNextFile();
            LogfileIndexer indexer;
            while (logfile != null)
            {
                try
                {
                    FileStream fileStream = new FileStream(logfile.Filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    indexer = new LogfileIndexer(fileStream);
                    this.lineIndexes = indexer.readLineIndexes(this.dataAccess);
                    logfile = this.dataAccess.FnProvider.GetNextFile();
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show("File cannot be accessed: " + e.Message);
                }
            }
        }
    }
}
